import router from './router'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { getToken } from '@/utils/auth'
import useSettingsStore from '@/store/modules/settings'
import { defineStore } from 'pinia'
import { constantRoutes } from '@/router'

console.log('Permission Store', constantRoutes);

NProgress.configure({ showSpinner: false })

const whiteList = ['/login', '/register', '/error'] // 无需登录的页面

router.beforeEach((to, from, next) => {
  NProgress.start()
  const token = getToken()

  if (token) {
    // ✅ 已登录
    to.meta.title && useSettingsStore().setTitle(to.meta.title)

    if (to.path === '/login') {
      next({ path: '/' }) // 登录后不再允许回登录页
    } else {
      next() // 放行其他路由
    }
  } else {
    // ❌ 未登录
    if (whiteList.includes(to.path)) {
      next() // 放行白名单页面
    } else {
      next(`/login?redirect=${to.fullPath}`) // 重定向到登录页
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})
const usePermissionStore = defineStore('permission', {
  state: () => ({
    routes: [],         // 左侧菜单要用的路由
    sidebarRoutes: []   // 保留副本，避免污染
  }),
  actions: {
    // 生成前端菜单路由
    generateRoutes() {
      return new Promise((resolve) => {
        this.routes = constantRoutes
        this.sidebarRoutes = constantRoutes
        resolve(constantRoutes)
      })
    }
  }
})
export default usePermissionStore

